import { Toast } from "antd-mobile"
import { reqlogin } from "../../http/api"

//状态
const initState = {
    //初始化user
    user: {
        phone: "",
        password: ""
    },
    userInfo:sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{}
}

const types = {
    //修改user type
    CHANGE_USER:"LOGIN_CHANGE_USER",
    //修改userInfo的type
    CHANGE_USER_INFO:"LOGIN_CHANGE_USER_INFO"
}

//reduce 修改state
const reducer = (state = initState,action)=>{
    switch (action.type){
        case types.CHANGE_USER:
            return{
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
        
        case types.CHANGE_USER_INFO:
            return{
                ...state,
                userInfo:action.userInfo
            }
    
        default:
            return state;
    }
}

//主要逻辑
export const actions = {
    changeUser:(key,value)=>({type:types.CHANGE_USER,key,value}),
    /* 点了登录 */
    reqLogin:(push)=>(dispatch,getState)=>{
        let user = getUser(getState())
        reqlogin(user).then(res=>{
            if(res.data.code === 200){
                Toast.show({
                    content:res.data.msg,
                })
                /* 存用户信息 */
                dispatch(actions.changeUserInfo(res.data.list));
                /* 跳转页面 */
                push("/index/home")
            }
        })
    },
    /* 修改userinfo的action */
    changeUserInfo:(userInfo) => {
        if(userInfo.token){
            sessionStorage.setItem("info",JSON.stringify(userInfo))
        } else {
            sessionStorage.removeItem("info")
        }
       return { type:types.CHANGE_USER_INFO, userInfo }
    }
}

//导出user
export const getUser = state => state.login.user;
// 导出userinfo
export const getUserInfo = state => state.login.userInfo; 

//导出reducer
export default reducer